        #include <stdio.h>
#include <stdlib.h>
#include "lc_array.h"
#include "lc_memory.h"

LCarray* lcArrayCreate()
{
    LCarray *array;
    array = (LCarray*) lcMalloc (sizeof (LCarray));
    (array)->memory = NULL;
    (array)->allocated = 0;
    (array)->used = 0;
    (array)->index = -1;
    return array;
}

int lcArrayAdd(LCarray *array, void *data)
{
    size_t toallocate;
    size_t size = sizeof (void*) ;
    if ((array->allocated - array->used) < size) {
        toallocate = array->allocated == 0 ? size : (array->allocated * 2);
        array->memory = realloc(array->memory, toallocate);
        array->allocated = toallocate;
    }

    array->memory[++array->index] = data;
    array->used = array->used + size;

    return array->index - 1;
}

int lcArrayLength(LCarray *array)
{
    return array->index + 1;
}

void lcArrayClear(LCarray *array)
{
    int i;
    for (i = 0; i < lcArrayLength(array); i++) {
        array->memory[i] = NULL;
    }
    array->used = 0;
    array->index = -1;
}

void lcArrayFree(LCarray *array)
{
    lcArrayClear(array);
    free(array->memory);
    free(array);
}

void* lcArrayGet(LCarray *array, int index)
{
    if (index < 0 || index > array->index)
        return NULL;

    return array->memory[index];
}

void lcArraySet(LCarray *array, int index, void *data)
{
    if (index < 0 || index > array->index)
        return;

    array->memory[index] = data;
}

void* lcArrayRemove(LCarray *array, int index)
{
    void* elmt;
    if (index < 0 || index > array->index)
        return;

    elmt = array->memory[index];
    array->memory[index] = NULL;
    return elmt;
}

